package org.gten.gegedexin.IMAP;

import org.gten.gegedexin.IMAP.IMAPClient;
import org.gten.gegedexin.IMAP.MailDigest;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import static org.gten.gegedexin.service.ReceiveFile.FILEPATH;

@Service
@EnableScheduling
public class GetMail {

    IMAPClient imapClient = new IMAPClient();
    @Scheduled(fixedDelay = 600000)
    public void storageMail() throws IOException {
        //  用IMAP收邮件
        ArrayList<MailDigest> maillist = imapClient.receiveUnseenMails();
        //  将获取的邮件正文存到本地
        String textPath = FILEPATH+"text/";
        String appendixPath = FILEPATH+"appendix/";
        File textfile = null;
        FileWriter writer = null;
        File targetDir = null;
        File targetFile = null;
        String fileName = null;
        if(maillist!=null){
            for(MailDigest mail:maillist){
                if(mail.getSubject().substring(0,1).equals('0')){
                    //  将正文存到本地，文件名为正文id
                    textfile = new File(textPath+mail.getSubject().substring(0,8)+".txt");
                    writer = new FileWriter(textfile);
                    writer.write(mail.getBody());
                }
                else if(mail.getSubject().substring(0,1).equals('1')){
                    //  创建附件的文件夹，文件夹名为附件id，若已存在该文件夹，则不创建
                    targetDir = new File(appendixPath+mail.getSubject().substring(0,8));
                    if(!targetDir.exists())
                        targetDir.mkdir();
                    //  将附件存入对应文件夹中
                    fileName = mail.getAttachment().getName();
                    targetFile = new File(appendixPath+mail.getSubject().substring(0,8)+'/'+fileName.substring(8));
                    mail.getAttachment().renameTo(targetFile);
                }
            }
        }
    }

}
